package problema092;

public class SquareDigitChains {
	
	static boolean[] base = new boolean[568];
	
	public static void main(String[] args){
		System.out.println(squareDigitChains());
	}
	
	public static int squareDigitChains(){
		int cant = 0, suma = 0, ultima = 0, a = 0;
		for(int i = 1; i < 568; i++){
			if(llegaA81(i)){
				base[i] = true;
				cant++;
			}else{ base[i] = false;}
		}		
		for(int i = 568; i < 10000000; i++){
			a = i; suma = 0; ultima = 0;
			while(a != 0){
				ultima = a % 10;
				suma += ultima * ultima;
				a = (a - ultima) / 10;
			}
			if(base[suma]) cant++;
		}
		return cant;
	}
	
	public static boolean llegaA81(int a){
		int suma = 0, ultima = 0;
		while(a != 0){
			ultima = a % 10;
			suma += ultima * ultima;
			a = (a - ultima) / 10;
		}
		if(suma == 1) return false;
		if(suma == 89) return true;
		return llegaA81(suma);
	}
}
